<template>
  <div class="users-container">
    <!-- 页面头部 -->
    <div class="page-header-wrapper">
      <div class="page-header">
        <div class="header-left">
          <h1 class="page-title">用户管理</h1>
          <p class="page-description">管理系统用户、角色和权限</p>
        </div>
        <div class="header-right">
          <el-button
            link
            size="default"
            @click="handleRefresh"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </div>
    <!-- page-header-wrapper 结束 -->

    <div class="content-section">
      <div class="content-layout">
        <!-- 左侧：部门树 -->
        <div class="left-sidebar" :class="{ 'is-collapsed': !departmentExpanded }">
          <el-card class="department-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span class="card-title" v-show="departmentExpanded">部门组织</span>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="departmentExpanded = !departmentExpanded"
                  :title="departmentExpanded ? '收拢' : '展开'"
                >
                  <el-icon>
                    <ArrowLeft v-if="departmentExpanded" />
                    <ArrowRight v-else />
                  </el-icon>
                </el-button>
              </div>
            </template>
            <div v-show="departmentExpanded" class="department-tree-wrapper">
              <DepartmentTree
                ref="departmentTreeRef"
                :selected-department-id="selectedDepartmentId"
                :include-users="true"
                :total-user-count="pagination.total"
                @node-click="handleDepartmentClick"
                @department-updated="handleDepartmentUpdated"
              />
            </div>
          </el-card>
        </div>
        <!-- left-sidebar 结束 -->

        <!-- 中间：筛选组件 -->
        <div class="middle-sidebar" :class="{ 'is-collapsed': !filtersExpanded }">
          <el-card class="filters-card" shadow="hover">
            <template #header>
              <div class="filters-card-header">
                <span class="card-title" v-show="filtersExpanded">筛选条件</span>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="filtersExpanded = !filtersExpanded"
                  :title="filtersExpanded ? '收拢' : '展开'"
                >
                  <el-icon>
                    <ArrowLeft v-if="filtersExpanded" />
                    <ArrowRight v-else />
                  </el-icon>
                </el-button>
              </div>
            </template>
            <!-- 筛选栏 - 紧凑型设计 -->
            <div class="filters-panel-compact" v-show="filtersExpanded">
              <!-- 顶部搜索栏 -->
              <div class="search-bar">
                <el-input
                  v-model="quickSearchText"
                  placeholder="快速搜索用户名、邮箱、手机号..."
                  clearable
                  size="default"
                  @keyup.enter="handleQuickSearch"
                  @clear="handleQuickSearchClear"
                  class="quick-search-input"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                  <template #suffix>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="handleQuickSearch"
                      :disabled="!quickSearchText"
                    >
                      搜索
                    </el-button>
                  </template>
                </el-input>
              </div>

              <!-- 筛选表单 -->
              <div class="filters-expanded">
                <el-form :model="searchForm" label-width="80px" class="filters-form">
                    <el-form-item label="用户名">
                <el-input
                  v-model="searchForm.username"
                  placeholder="请输入用户名"
                  clearable
                  size="default"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon><UserIcon /></el-icon>
                  </template>
                </el-input>
                    </el-form-item>
                    
                    <el-form-item label="邮箱">
                <el-input
                  v-model="searchForm.email"
                  placeholder="请输入邮箱"
                  clearable
                  size="default"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
                    </el-form-item>
                    
                    <el-form-item label="手机号">
                <el-input
                  v-model="searchForm.phone"
                  placeholder="请输入手机号"
                  clearable
                  size="default"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
                    </el-form-item>
                    
                    <el-form-item label="角色">
                <el-select 
                  v-model="searchForm.role" 
                  placeholder="选择角色" 
                  clearable
                  filterable
                  size="default"
                  style="width: 100%"
                  :loading="roleStore.loading"
                  @visible-change="(visible: boolean) => visible && ensureRoleOptionsLoaded(true, true).catch(() => {})"
                >
                  <el-option 
                    v-for="role in roleSelectOptions" 
                    :key="role.value" 
                    :label="role.label" 
                    :value="role.value" 
                  />
                </el-select>
                    </el-form-item>
                    
                    <el-form-item label="状态">
                <el-select 
                  v-model="searchForm.status" 
                  placeholder="选择状态" 
                  clearable
                  size="default"
                  style="width: 100%"
                >
                  <el-option label="激活" value="active">
                    <el-tag type="success" size="small">激活</el-tag>
                  </el-option>
                  <el-option label="禁用" value="inactive">
                    <el-tag type="danger" size="small">禁用</el-tag>
                  </el-option>
                </el-select>
                    </el-form-item>

                    <!-- 快速筛选标签 -->
                    <el-form-item v-if="quickFilterTags.length > 0" class="quick-filters-item">
                <div class="quick-filters">
                  <div class="quick-filters-label">已选筛选：</div>
                  <div class="quick-filters-tags">
                    <el-tag
                      v-for="tag in quickFilterTags"
                      :key="tag.key"
                      :type="tag.type"
                      size="small"
                      closable
                      @close="handleRemoveFilterTag(tag.key)"
                      class="filter-tag"
                    >
                      {{ tag.label }}
                    </el-tag>
                  </div>
                </div>
                    </el-form-item>
                    
                    <!-- 筛选操作按钮 -->
                    <el-form-item class="filters-actions-item">
                <div class="filters-actions">
                  <el-button 
                    @click="handleReset" 
                    :disabled="!hasActiveFilters"
                    size="default"
                    plain
                  >
                    <el-icon><Refresh /></el-icon>
                    重置筛选
                  </el-button>
                </div>
              </el-form-item>
                </el-form>
              </div>
            </div>
          </el-card>
        </div>
        <!-- middle-sidebar 结束 -->

        <!-- 右侧：用户列表 -->
        <div class="right-content">
          <!-- 列表区域 -->
          <div class="table-wrapper">
          <div v-if="selectedUsers.length > 0" class="batch-actions">
            <el-card>
              <div class="batch-content">
                <span class="batch-info">已选择 {{ selectedUsers.length }} 个用户</span>
                <div class="batch-buttons">
                  <el-button type="success" @click="handleBatchActivate">
                    <el-icon><Check /></el-icon>
                    批量启用
                  </el-button>
                  <el-button type="warning" @click="handleBatchDeactivate">
                    <el-icon><Close /></el-icon>
                    批量禁用
                  </el-button>
                  <el-button type="danger" @click="handleBatchDelete">
                    <el-icon><Delete /></el-icon>
                    批量删除
                  </el-button>
                </div>
              </div>
            </el-card>
          </div>

          <div class="table-section">
            <el-card class="table-card" shadow="hover">
              <template #header>
                <div class="table-header">
                  <div class="table-header-left">
                    <span class="table-title">用户列表</span>
                    <el-tag type="info" size="small" v-if="pagination.total > 0">
                      共 {{ pagination.total }} 条
                    </el-tag>
                  </div>
                  <div class="table-header-right">
                    <el-button @click="handleExportUsers">
                      <el-icon><Download /></el-icon>
                      导出用户
                    </el-button>
                    <el-button @click="handleImportUsers">
                      <el-icon><Upload /></el-icon>
                      导入用户
                    </el-button>
                    <el-button type="primary" @click="handleCreateUser">
                      <el-icon><Plus /></el-icon>
                      新增用户
                    </el-button>
                  </div>
                </div>
              </template>
              
              <div class="table-scroll" ref="tableSectionRef">
                <el-table
                  v-loading="loading"
                  :data="users"
                  :height="tableHeight"
                  stripe
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  :header-cell-style="{ 
                    height: '48px',
                    background: '#fafafa',
                    color: '#606266',
                    fontWeight: '600'
                  }"
                  :row-style="{ height: '64px' }"
                  :max-height="tableHeight"
                  table-layout="auto"
                  class="users-table"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  
                  <el-table-column label="用户信息" min-width="220" fixed="left">
                    <template #default="{ row }">
                      <div class="user-info-cell">
                        <el-avatar 
                          :src="getAvatarUrl(row.avatar)" 
                          :size="40"
                          class="user-avatar"
                        >
                          {{ (row.name || row.username || '').charAt(0).toUpperCase() }}
                        </el-avatar>
                        <div class="user-details">
                          <div class="user-name">
                            <span class="name-text">{{ row.name || row.username }}</span>
                            <el-tag 
                              :type="getStatusTagType(row.status)"
                              size="small"
                              effect="plain"
                              class="status-tag"
                            >
                              {{ getStatusLabel(row.status) }}
                            </el-tag>
                          </div>
                          <div class="user-meta">
                            <span class="username-text">@{{ row.username }}</span>
                            <el-divider direction="vertical" />
                            <span class="email-text">{{ row.email }}</span>
                          </div>
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  
                  <el-table-column prop="department" label="部门" min-width="120" show-overflow-tooltip>
                    <template #default="{ row }">
                      <span v-if="row.department">{{ row.department }}</span>
                      <span v-else class="empty-text">—</span>
                    </template>
                  </el-table-column>
                  
                  <el-table-column prop="position" label="职位" min-width="120" show-overflow-tooltip>
                    <template #default="{ row }">
                      <span v-if="row.position">{{ row.position }}</span>
                      <span v-else class="empty-text">—</span>
                    </template>
                  </el-table-column>
                  
                  <el-table-column prop="phone" label="手机号" min-width="130" show-overflow-tooltip>
                    <template #default="{ row }">
                      <span v-if="row.phone">{{ row.phone }}</span>
                      <span v-else class="empty-text">—</span>
                    </template>
                  </el-table-column>
                  
                  <el-table-column label="角色" min-width="180">
                    <template #default="{ row }">
                      <div class="roles-container">
                        <el-tag
                          v-for="role in row.roles"
                          :key="role"
                          :type="getRoleTagType(role)"
                          size="small"
                          effect="plain"
                          class="role-tag"
                        >
                          {{ getRoleLabel(role) }}
                        </el-tag>
                        <span v-if="!row.roles || row.roles.length === 0" class="empty-text">—</span>
                      </div>
                    </template>
                  </el-table-column>
                  
                  <el-table-column prop="last_login" label="最后登录" width="170">
                    <template #default="{ row }">
                      <div class="time-cell">
                        <el-icon><Clock /></el-icon>
                        <span>{{ row.last_login ? formatDate(row.last_login) : '从未登录' }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  
                  <el-table-column prop="created_at" label="创建时间" width="170">
                    <template #default="{ row }">
                      <div class="time-cell">
                        <el-icon><Calendar /></el-icon>
                        <span>{{ formatDate(row.created_at) }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  
                  <el-table-column prop="updated_at" label="更新时间" width="170">
                    <template #default="{ row }">
                      <div class="time-cell">
                        <el-icon><Clock /></el-icon>
                        <span>{{ formatDate(row.updated_at) }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                      <div class="action-buttons">
                        <el-button
                          link
                          type="primary"
                          size="small"
                          :disabled="isSystemAdmin(row)"
                          @click="handleEditUser(row)"
                          class="action-btn"
                          :title="isSystemAdmin(row) ? '系统管理员不可编辑' : ''"
                        >
                          <el-icon><Edit /></el-icon>
                          编辑
                        </el-button>
                        <el-dropdown 
                          trigger="click"
                          @command="(command: string) => handleActionCommand(command, row)"
                        >
                          <el-button link type="primary" size="small" class="action-btn">
                            <el-icon><MoreFilled /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item 
                                command="reset-password"
                                :disabled="isSystemAdmin(row)"
                              >
                                <el-icon><Key /></el-icon>
                                重置密码
                              </el-dropdown-item>
                              <el-dropdown-item 
                                :command="row.status === 'active' ? 'deactivate' : 'activate'"
                                :divided="row.status === 'active'"
                                :disabled="isSystemAdmin(row)"
                              >
                                <el-icon>
                                  <CircleCheck v-if="row.status === 'inactive'" />
                                  <CircleClose v-else />
                                </el-icon>
                                {{ row.status === 'active' ? '禁用' : '启用' }}
                              </el-dropdown-item>
                              <el-dropdown-item 
                                command="delete"
                                divided
                                :disabled="isDefaultAdmin(row)"
                              >
                                <el-icon><Delete /></el-icon>
                                <span :style="{ color: isDefaultAdmin(row) ? '#c0c4cc' : '#f56c6c' }">删除</span>
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <!-- 分页 -->
              <div class="pagination-wrapper">
                <el-pagination
                  v-model:current-page="pagination.page"
                  v-model:page-size="pagination.size"
                  :total="pagination.total"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </div>
        </div>
        <!-- table-wrapper 结束 -->
      </div>
      <!-- right-content 结束 -->
    </div>
    <!-- content-layout 结束 -->
    </div>
    <!-- content-section 结束 -->

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEditMode ? '编辑用户' : '新增用户'"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="user-dialog"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="120px"
        class="user-form"
      >
        <!-- 基本信息 -->
         <div class="form-section">
           <div class="section-title">
             <el-icon><UserIcon /></el-icon>
             <span>基本信息</span>
           </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="userForm.username"
                  placeholder="请输入用户名"
                  :disabled="isEditMode || (isEditMode && isSystemAdmin({ username: userForm.username || '', roles: userForm.roles || [] } as User))"
                  :prefix-icon="UserIcon"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="userForm.email"
                  placeholder="请输入邮箱"
                  type="email"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="userForm.name"
                  placeholder="请输入姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="userForm.phone"
                  placeholder="请输入手机号号码"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 组织信息 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><OfficeBuilding /></el-icon>
            <span>组织信息</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门" prop="department">
                <el-select
                  v-model="userForm.department"
                  placeholder="请选择部门"
                  clearable
                  filterable
                  style="width: 100%"
                  :loading="departmentLoading"
                  @visible-change="(visible: boolean) => visible && loadDepartmentList()"
                >
                  <el-option
                    v-for="dept in departmentList"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.name"
                  >
                    <div style="display: flex; align-items: center; gap: 8px;">
                      <el-icon><OfficeBuilding /></el-icon>
                      <span>{{ dept.name }}</span>
                      <span v-if="dept.user_count !== undefined && dept.user_count > 0" style="color: #909399; font-size: 12px;">
                        ({{ dept.user_count }}人)
                      </span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职位" prop="position">
                <el-input
                  v-model="userForm.position"
                  placeholder="请输入职位"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 安全设置 -->
        <div class="form-section" v-if="!isEditMode">
          <div class="section-title">
            <el-icon><Lock /></el-icon>
            <span>安全设置</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="userForm.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 权限设置 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Setting /></el-icon>
            <span>权限设置</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色" prop="roles">
                <el-select
                  v-model="userForm.roles"
                  multiple
                  placeholder="选择角色"
                  style="width: 100%"
                  collapse-tags
                  collapse-tags-tooltip
                  :disabled="isEditMode && isSystemAdmin({ username: userForm.username || '', roles: userForm.roles || [] } as User)"
                  :loading="roleStore.loading"
                  @visible-change="(visible: boolean) => visible && ensureRoleOptionsLoaded(true, true).catch(() => {})"
                >
                  <el-option 
                    v-for="role in roleSelectOptions" 
                    :key="role.value" 
                    :label="role.label" 
                    :value="role.value"
                  >
                    <el-icon><Star v-if="role.value === 'admin'" /><UserFilled v-else /></el-icon>
                    <span style="margin-left: 8px;">{{ role.label }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select
                  v-model="userForm.status"
                  placeholder="选择状态"
                  style="width: 100%"
                >
                  <el-option label="激活" value="active">
                    <el-icon><Check /></el-icon>
                    <span style="margin-left: 8px;">激活</span>
                  </el-option>
                  <el-option label="禁用" value="inactive">
                    <el-icon><CircleClose /></el-icon>
                    <span style="margin-left: 8px;">禁用</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 个人简介 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon><Document /></el-icon>
            <span>个人简介</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="个人简介" prop="bio">
                <el-input
                  v-model="userForm.bio"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入个人简介（可选）"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userDialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" :loading="saving" @click="handleSaveUser" size="large">
            <el-icon><Check /></el-icon>
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入用户对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入用户"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="1"
        accept=".xlsx,.xls,.csv"
        :on-change="handleFileChange"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 xlsx/xls/csv 文件，且不超过 10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="importing" @click="handleConfirmImport">
          确认导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Refresh, Download, Upload, UserFilled, 
  Check, Close, Delete, UploadFilled, User as UserIcon,
  OfficeBuilding, Lock, Setting, Star, CircleClose,
  Document, Search, Message, Phone,
  Edit, MoreFilled, Key, CircleCheck, Clock, Calendar,
  ArrowLeft, ArrowRight
} from '@element-plus/icons-vue'
import { 
  getUsers, createUser, updateUser, deleteUser, batchDeleteUsers,
  resetUserPassword, getUserStats, exportUsers, importUsers,
  batchActivateUsers, batchDeactivateUsers, toggleUserStatus, getUserCount
} from '@/api/users'
import { ResponseParser } from '@/utils/responseParser'
import { getAvatarUrl } from '@/utils/avatar'
import type { User, CreateUserParams, UpdateUserParams, UserStats } from '@/types/user'
import { useRoleStore } from '@/stores'
import DepartmentTree from '@/components/department/DepartmentTree.vue'
import type { Department } from '@/types/department'
import { getDepartmentList } from '@/api/departments'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const importing = ref(false)
const users = ref<User[]>([])
const selectedUsers = ref<User[]>([])
const userDialogVisible = ref(false)
const importDialogVisible = ref(false)
const isEditMode = ref(false)
const userFormRef = ref()
const uploadRef = ref()
const importFile = ref<File | null>(null)

// 部门树相关
const departmentTreeRef = ref<InstanceType<typeof DepartmentTree> | null>(null)
const selectedDepartmentId = ref<string>('')

// 筛选条件展开状态
const filtersExpanded = ref(true)
// 部门组织展开状态
const departmentExpanded = ref(true)

// 部门列表（用于下拉选择）
const departmentList = ref<Department[]>([])
const departmentLoading = ref(false)

// 列表高度控制
const TABLE_HEADER_HEIGHT = 46
const TABLE_ROW_HEIGHT = 46
const MAX_VISIBLE_ROWS = 10
const tableHeight = ref<number>(480)
const tableSectionRef = ref<HTMLElement | null>(null)

// 用户统计
const userStats = reactive<UserStats>({
  total_users: 0,
  active_users: 0,
  inactive_users: 0,
  new_users_this_month: 0,
  user_growth_rate: 0
})

// 角色字典

const roleStore = useRoleStore()
const { roleOptions } = storeToRefs(roleStore)

// 用户管理中的角色选项：只显示系统级角色（管理员和普通用户）
const roleSelectOptions = computed(() => {
  // 只显示系统级角色：admin 和 user
  return roleOptions.value.filter(role => {
    const code = role.value?.toLowerCase() || ''
    return code === 'admin' || code === 'user'
  })
})

const ensureRoleOptionsLoaded = async (force = false, showFeedback = false) => {
  try {
    const result = await roleStore.fetchRoles(force)
    if (showFeedback && (!result || result.length === 0)) {
      ElMessage.warning('未获取到角色数据，请确认当前账号是否具备查看角色权限')
    }
    return result
  } catch (error: any) {
    console.error('加载角色数据失败:', error)
    if (showFeedback) {
      ElMessage.error(error?.message || '加载角色数据失败')
    }
    throw error
  }
}

// 快速搜索
const quickSearchText = ref('')

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  phone: '',
  role: '',
  status: '',
  department: '' // 部门筛选（通过部门树选择）
})

// 计算是否有活动的筛选条件
const hasActiveFilters = computed(() => {
  return !!(
    searchForm.username ||
    searchForm.email ||
    searchForm.phone ||
    searchForm.role ||
    searchForm.status ||
    searchForm.department ||
    quickSearchText.value
  )
})

// 快速筛选标签
const quickFilterTags = computed(() => {
  const tags: Array<{ key: string; label: string; type: 'primary' | 'success' | 'warning' | 'danger' | 'info' }> = []
  if (searchForm.role) {
    const role = roleSelectOptions.value.find(r => r.value === searchForm.role)
    if (role) {
      tags.push({ key: 'role', label: `角色: ${role.label}`, type: 'primary' })
    }
  }
  if (searchForm.status) {
    tags.push({ 
      key: 'status', 
      label: `状态: ${searchForm.status === 'active' ? '激活' : '禁用'}`, 
      type: searchForm.status === 'active' ? 'success' : 'danger' 
    })
  }
  if (searchForm.department || selectedDepartmentId.value) {
    const deptName = selectedDepartment.value?.name || '已选择'
    tags.push({ 
      key: 'department', 
      label: `部门: ${deptName}`, 
      type: 'info' 
    })
  }
  return tags
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 用户表单
const userForm = reactive<CreateUserParams & { id?: string; department?: string; position?: string; bio?: string }>({
  username: '',
  email: '',
  name: '',
  phone: '',
  password: '',
  department: '',
  position: '',
  bio: '',
  roles: [],
  status: 'active'
})

// 表单验证规则
const userFormRules: any = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取用户统计
const fetchUserStats = async () => {
  try {
    const response = await getUserStats()
    // getUserStats 已经处理了统一响应格式并返回了标准格式的数据
    if (response && typeof response === 'object') {
      Object.assign(userStats, response)
    } else {
      // 如果返回的不是对象，使用默认值
      Object.assign(userStats, {
        total_users: 0,
        active_users: 0,
        inactive_users: 0,
        new_users_this_month: 0,
        user_growth_rate: 0
      })
      ElMessage.warning('获取用户统计失败，显示默认数据')
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
    
    // 设置默认统计数据，确保界面正常显示
    Object.assign(userStats, {
      total_users: 0,
      active_users: 0,
      inactive_users: 0,
      new_users_this_month: 0,
      user_growth_rate: 0
    })
    
    ElMessage.warning('获取用户统计失败，显示默认数据')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true

    const searchTokens = [searchForm.username, searchForm.email, searchForm.phone]
      .map(value => (typeof value === 'string' ? value.trim() : ''))
      .filter(token => token.length > 0)
    const searchKeyword = searchTokens.length > 0 ? Array.from(new Set(searchTokens)).join(' ') : undefined

    // 构建查询参数
    const params = {
      page: pagination.page,
      size: pagination.size,
      username: searchForm.username || undefined,
      email: searchForm.email || undefined,
      phone: searchForm.phone || undefined,
      status: searchForm.status || undefined,
      role: searchForm.role || undefined,
      department: searchForm.department || selectedDepartmentId.value || undefined,
      search: searchKeyword,
      sort_by: 'created_at',
      sort_order: 'desc' as const
    }

    // 调用API
    const response = await getUsers(params)

    // 使用公共解析方法处理响应数据
    const parsedResult = ResponseParser.parseUserListResponse(response)

    users.value = parsedResult.items

    const totalFromResponse = parsedResult.pagination?.total ?? parsedResult.total ?? parsedResult.items.length
    pagination.total = typeof totalFromResponse === 'number' ? totalFromResponse : parsedResult.items.length

    if (parsedResult.pagination) {
      pagination.page = parsedResult.pagination.page ?? pagination.page
      pagination.size = parsedResult.pagination.size ?? pagination.size
    } else {
      try {
        const countResponse = await getUserCount({
          search: searchKeyword,
          status: params.status,
          role: params.role
        })
        const countResult = ResponseParser.parseResponse(countResponse)
        if (countResult.success && countResult.data && typeof countResult.data === 'object' && 'total' in countResult.data) {
          pagination.total = (countResult.data as any).total
        }
      } catch (countError) {
        console.warn('获取用户总数失败，使用解析结果:', countError)
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    // 用户数据加载失败时设置为空数组，不使用备用数据
    users.value = []
    pagination.total = 0
  } finally {
    loading.value = false
    nextTick(() => {
      updateTableHeight()
    })
  }
}

// 快速搜索
const handleQuickSearch = () => {
  if (!quickSearchText.value.trim()) {
    return
  }
  
  // 将快速搜索文本分配到各个字段
  const searchText = quickSearchText.value.trim()
  
  // 检查是否为邮箱格式
  if (searchText.includes('@')) {
    searchForm.email = searchText
    searchForm.username = ''
    searchForm.phone = ''
  } 
  // 检查是否为手机号格式
  else if (/^1[3-9]\d{9}$/.test(searchText)) {
    searchForm.phone = searchText
    searchForm.username = ''
    searchForm.email = ''
  }
  // 默认为用户名
  else {
    searchForm.username = searchText
    searchForm.email = ''
    searchForm.phone = ''
  }
  
  pagination.page = 1
  fetchUsers()
}

// 清除快速搜索
const handleQuickSearchClear = () => {
  quickSearchText.value = ''
  searchForm.username = ''
  searchForm.email = ''
  searchForm.phone = ''
  pagination.page = 1
  fetchUsers()
}

// 搜索（保留用于手动触发）
const handleSearch = () => {
  pagination.page = 1
  fetchUsers()
}

// 防抖定时器
let searchTimer: ReturnType<typeof setTimeout> | null = null

// 实时搜索：监听筛选条件变化，自动触发查询
watch(
  () => [
    searchForm.username,
    searchForm.email,
    searchForm.phone,
    searchForm.role,
    searchForm.status,
    searchForm.department,
    selectedDepartmentId.value
  ],
  () => {
    // 清除之前的定时器
    if (searchTimer) {
      clearTimeout(searchTimer)
    }
    
    // 设置防抖，300ms后执行查询
    searchTimer = setTimeout(() => {
      pagination.page = 1
      fetchUsers()
    }, 300)
  },
  { deep: true }
)

// 重置搜索
const handleReset = () => {
  quickSearchText.value = ''
  selectedDepartmentId.value = ''
  Object.assign(searchForm, {
    username: '',
    email: '',
    phone: '',
    role: '',
    status: '',
    department: ''
  })
  // 重置部门树选中状态
  if (departmentTreeRef.value && 'setCurrentKey' in departmentTreeRef.value) {
    (departmentTreeRef.value as any).setCurrentKey(null)
  }
  pagination.page = 1
  fetchUsers()
}

// 移除筛选标签
const handleRemoveFilterTag = (key: string) => {
  if (key === 'role') {
    searchForm.role = ''
  } else if (key === 'status') {
    searchForm.status = ''
  } else if (key === 'department') {
    searchForm.department = ''
    selectedDepartmentId.value = ''
    if (departmentTreeRef.value && 'setCurrentKey' in departmentTreeRef.value) {
      (departmentTreeRef.value as any).setCurrentKey(null)
    }
  }
  pagination.page = 1
  fetchUsers()
}

// 当前选中的部门信息（用于显示部门名称）
const selectedDepartment = ref<Department | null>(null)

// 部门树数据（用于获取子部门）
const departmentTreeData = ref<Department[]>([])

// 递归获取部门及其所有子部门的ID
const getAllDepartmentIds = (department: Department, departmentTree: Department[]): string[] => {
  const ids: string[] = [department.id]
  
  // 在部门树中查找该部门
  const findDepartment = (tree: Department[], targetId: string): Department | null => {
    for (const dept of tree) {
      if (dept.id === targetId) {
        return dept
      }
      if (dept.children && dept.children.length > 0) {
        const found = findDepartment(dept.children, targetId)
        if (found) return found
      }
    }
    return null
  }
  
  const deptWithChildren = findDepartment(departmentTree, department.id)
  if (deptWithChildren && deptWithChildren.children && deptWithChildren.children.length > 0) {
    // 递归获取所有子部门的ID
    const getChildrenIds = (children: Department[]): string[] => {
      const childIds: string[] = []
      for (const child of children) {
        childIds.push(child.id)
        if (child.children && child.children.length > 0) {
          childIds.push(...getChildrenIds(child.children))
        }
      }
      return childIds
    }
    ids.push(...getChildrenIds(deptWithChildren.children))
  }
  
  return ids
}

// 部门树节点点击处理
const handleDepartmentClick = (department: Department | null) => {
  if (department) {
    // 点击部门，筛选该部门及其所有子部门的用户
    selectedDepartmentId.value = department.id
    selectedDepartment.value = department
    
    // 获取部门树数据（从部门树组件获取）
    if (departmentTreeRef.value) {
      const treeData = (departmentTreeRef.value as any).departmentTree || departmentTreeData.value
      const allDeptIds = getAllDepartmentIds(department, treeData)
      // 将部门ID列表用逗号分隔传递给后端
      searchForm.department = allDeptIds.join(',')
    } else {
      // 如果无法获取部门树，只使用当前部门ID
      searchForm.department = department.id
    }
  } else {
    // 点击根节点（全部用户），显示所有用户
    selectedDepartmentId.value = ''
    selectedDepartment.value = null
    searchForm.department = ''
  }
  pagination.page = 1
  fetchUsers()
}

// 部门更新后刷新
const handleDepartmentUpdated = () => {
  // 部门更新后，刷新用户列表和部门列表
  departmentList.value = [] // 清空部门列表，下次打开对话框时重新加载
  // 更新部门树数据
  if (departmentTreeRef.value) {
    departmentTreeData.value = (departmentTreeRef.value as any).departmentTree || []
  }
  fetchUsers()
}

// 刷新列表
const handleRefresh = () => {
  fetchUsers()
  fetchUserStats()
}

// 处理操作命令
const handleActionCommand = (command: string, row: User) => {
  // 检查是否为系统管理员
  if (isSystemAdmin(row)) {
    if (command !== 'delete' || !isDefaultAdmin(row)) {
      ElMessage.warning('系统管理员不可执行此操作')
      return
    }
  }
  
  switch (command) {
    case 'reset-password':
      handleResetPassword(row)
      break
    case 'activate':
    case 'deactivate':
      handleToggleStatus(row)
      break
    case 'delete':
      handleDeleteUser(row)
      break
  }
}

// 移除自动搜索，改为手动搜索
// watch(
//   () => [searchForm.username, searchForm.email, searchForm.phone],
//   () => {
//     pagination.page = 1
//     fetchUsers()
//   }
// )

// watch(
//   () => [searchForm.role, searchForm.status],
//   () => {
//     pagination.page = 1
//     fetchUsers()
//   }
// )

const updateTableHeight = () => {
  if (!tableSectionRef.value) return
  const tableCardBody = tableSectionRef.value.closest('.el-card__body') as HTMLElement
  if (!tableCardBody) return
  
  const cardBodyRect = tableCardBody.getBoundingClientRect()
  
  // 获取分页组件的高度
  const paginationEl = tableCardBody.querySelector('.pagination-wrapper') as HTMLElement
  const paginationHeight = paginationEl ? paginationEl.offsetHeight : 60
  
  // 获取表格头部高度
  const tableHeader = tableSectionRef.value.querySelector('.el-table__header-wrapper') as HTMLElement
  const headerHeight = tableHeader ? tableHeader.offsetHeight : TABLE_HEADER_HEIGHT
  
  // 计算可用高度：卡片body高度 - 表格头部 - 分页高度 - padding
  const bodyPadding = 16 // 卡片body的padding
  const calculated = cardBodyRect.height - headerHeight - paginationHeight - bodyPadding * 2

  const visibleRows = Math.min(pagination.size, MAX_VISIBLE_ROWS)
  const desiredHeight = TABLE_HEADER_HEIGHT + visibleRows * TABLE_ROW_HEIGHT

  tableHeight.value = Math.max(
    Math.min(calculated, desiredHeight),
    TABLE_HEADER_HEIGHT + 3 * TABLE_ROW_HEIGHT // 至少显示3行
  )
}

const handleWindowResize = () => {
  updateTableHeight()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchUsers()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchUsers()
}

// 选择变化处理
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection
}

// 批量操作
const handleBatchActivate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要启用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const userIds = selectedUsers.value.map(user => user.id)
    const response = await batchActivateUsers(userIds)
    
    // 处理统一响应格式 {success, data, message}
    if (response && response.data && response.data.success) {
      ElMessage.success(response.data.message || '批量启用成功')
    } else {
      ElMessage.error(response?.data?.message || '批量启用失败')
    }
    
    selectedUsers.value = []
    fetchUsers()
    fetchUserStats() // 更新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量启用失败:', error)
      ElMessage.error('批量启用失败')
    }
  }
}

const handleBatchDeactivate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要禁用选中的 ${selectedUsers.value.length} 个用户吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const userIds = selectedUsers.value.map(user => user.id)
    const response = await batchDeactivateUsers(userIds)
    
    // 处理统一响应格式 {success, data, message}
    if (response && response.data && response.data.success) {
      ElMessage.success(response.data.message || '批量禁用成功')
    } else {
      ElMessage.error(response?.data?.message || '批量禁用失败')
    }
    
    selectedUsers.value = []
    fetchUsers()
    fetchUserStats() // 更新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量禁用失败:', error)
      ElMessage.error('批量禁用失败')
    }
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const userIds = selectedUsers.value.map(user => user.id)
    const response = await batchDeleteUsers(userIds)
    
    // 处理统一响应格式 {success, data, message}
    if (response && response.data && response.data.success) {
      ElMessage.success(response.data.message || '批量删除成功')
    } else {
      ElMessage.error(response?.data?.message || '批量删除失败')
    }
    
    selectedUsers.value = []
    fetchUsers()
    fetchUserStats() // 更新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 导出用户
const handleExportUsers = async () => {
  try {
    loading.value = true
    const response = await exportUsers(searchForm)
    
    // 检查响应类型
    let blob: Blob | null = null
    
    if (response instanceof Blob) {
      // 直接是Blob类型
      blob = response
    } else if (response?.data instanceof Blob) {
      // 包装在data中的Blob
      blob = response.data
    } else if (response?.data) {
      // 可能是其他格式，尝试创建Blob
      blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
      })
    }
    
    if (blob) {
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      const dateStr = new Date().toISOString().split('T')[0]
      link.download = `users_export_${dateStr}.xlsx`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('用户数据导出成功')
    } else {
      ElMessage.error('导出失败：无法获取文件数据')
    }
  } catch (error: any) {
    console.error('导出用户失败:', error)
    const errorMessage = error?.response?.data?.message || error?.message || '导出用户失败，请稍后重试'
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 导入用户
const handleImportUsers = () => {
  importDialogVisible.value = true
}

const handleFileChange = (file: any) => {
  importFile.value = file.raw
  // 验证文件类型
  const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
    'application/vnd.ms-excel', // .xls
    'text/csv' // .csv
  ]
  
  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error('只支持 Excel (.xlsx, .xls) 和 CSV (.csv) 文件')
    importFile.value = null
    return false
  }
  
  // 验证文件大小 (限制为10MB)
  const maxSize = 10 * 1024 * 1024
  if (file.raw.size > maxSize) {
    ElMessage.error('文件大小不能超过 10MB')
    importFile.value = null
    return false
  }
  
  return true
}

const handleConfirmImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  try {
    importing.value = true
    const response = await importUsers(importFile.value)
    
    // 处理统一响应格式 {success, data, message}
    // response可能是 {data: {success, data, message}} 或直接是 {success, data, message}
    const responseData = response?.data || response
    
    if (responseData && responseData.success) {
      const successCount = responseData.data?.success_count || 0
      const errorCount = responseData.data?.error_count || 0
      
      ElMessage.success(
        responseData.message || `导入完成！成功: ${successCount}，失败: ${errorCount}`
      )
      
      if (responseData.data?.errors && responseData.data.errors.length > 0) {
        // 显示详细错误信息
        const errorMessages = responseData.data.errors.slice(0, 10).join('\n')
        const hasMore = responseData.data.errors.length > 10
        ElMessageBox.alert(
          `导入过程中发现以下错误（${responseData.data.errors.length}个）：\n\n${errorMessages}${hasMore ? '\n\n...还有更多错误，请检查文件后重试' : ''}`,
          '导入警告',
          { 
            type: 'warning',
            confirmButtonText: '确定',
            dangerouslyUseHTMLString: false
          }
        )
      }
      
      importDialogVisible.value = false
      importFile.value = null
      uploadRef.value?.clearFiles()
      fetchUsers()
      fetchUserStats()
    } else {
      const errorMessage = responseData?.message || (response as any)?.message || '导入失败'
      ElMessage.error(errorMessage)
    }
  } catch (error: any) {
    console.error('导入用户失败:', error)
    const errorMessage = error?.response?.data?.message || error?.response?.data?.detail || error?.message || '导入用户失败，请检查文件格式'
    ElMessage.error(errorMessage)
  } finally {
    importing.value = false
  }
}

// 加载部门列表（扁平化，用于下拉选择）
const loadDepartmentList = async () => {
  if (departmentList.value.length > 0) {
    return // 已经加载过，不需要重复加载
  }
  
  departmentLoading.value = true
  try {
    const response = await getDepartmentList({ tree: false, include_users: true })
    // 处理API响应格式：response.data 是 axios 响应，response.data.data 是实际的 API 响应数据
    const apiResponse = response?.data as any
    if (apiResponse && typeof apiResponse === 'object' && 'success' in apiResponse) {
      // API 响应格式：{ success: true, data: {...} }
      if (apiResponse.success && apiResponse.data) {
        const data = apiResponse.data
        departmentList.value = Array.isArray(data.items) ? data.items : (Array.isArray(data) ? data : [])
      } else {
        departmentList.value = []
      }
    } else if (Array.isArray(apiResponse)) {
      // 直接返回数组的情况
      departmentList.value = apiResponse
    } else {
      departmentList.value = []
    }
  } catch (error) {
    console.error('加载部门列表失败:', error)
    departmentList.value = []
  } finally {
    departmentLoading.value = false
  }
}

// 新增用户
const handleCreateUser = async () => {
  await ensureRoleOptionsLoaded(true, true).catch(() => {})
  await loadDepartmentList()
  isEditMode.value = false
  resetUserForm()
  userDialogVisible.value = true
}

// 编辑用户
const handleEditUser = async (user: User) => {
  // 检查是否为系统管理员
  if (isSystemAdmin(user)) {
    ElMessage.warning('系统管理员不可编辑')
    return
  }
  
  await ensureRoleOptionsLoaded(true, true).catch(() => {})
  await loadDepartmentList()
  isEditMode.value = true
  Object.assign(userForm, {
    id: user.id,
    username: user.username,
    email: user.email,
    name: user.name,
    phone: user.phone,
    department: user.department || '',
    position: user.position || '',
    bio: user.bio || '',
    roles: user.roles,
    status: user.status
  })
  userDialogVisible.value = true
}

// 保存用户
const handleSaveUser = async () => {
  try {
    await userFormRef.value?.validate()
    
    saving.value = true
    
    // 转换角色ID为角色值（后端期望的是角色值字符串数组）
    const convertRolesToValues = (roleIds: any[]): string[] => {
      if (!Array.isArray(roleIds)) return []
      return roleIds.map(roleId => {
        if (typeof roleId !== 'string') {
          roleId = String(roleId)
        }
        const roleByCode = roleStore.roleMap[roleId]
        if (roleByCode) {
          return roleByCode.code
        }
        const roleById = Object.values(roleStore.roleMap).find(r => r.id === roleId)
        if (roleById) {
          return roleById.code
        }
        return roleId
      }).filter(Boolean)
    }
    
    const roleValues = convertRolesToValues(userForm.roles)
    
    if (isEditMode.value) {
      // 更新用户
      const updateData: UpdateUserParams & { department?: string; position?: string; bio?: string } = {
        email: userForm.email,
        name: userForm.name,
        phone: userForm.phone,
        department: userForm.department,
        position: userForm.position,
        bio: userForm.bio,
        roles: roleValues,
        status: userForm.status
      }
      
      await updateUser(userForm.id!, updateData)
      ElMessage.success('用户更新成功')
    } else {
      // 创建用户
      const createData: CreateUserParams & { department?: string; position?: string; bio?: string } = {
        username: userForm.username,
        email: userForm.email,
        name: userForm.name,
        phone: userForm.phone,
        password: userForm.password,
        department: userForm.department,
        position: userForm.position,
        bio: userForm.bio,
        roles: roleValues,
        status: userForm.status
      }
      
      await createUser(createData)
      ElMessage.success('用户创建成功')
    }
    
    userDialogVisible.value = false
    fetchUsers()
    fetchUserStats()
  } catch (error: any) {
    console.error('保存用户失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '保存用户失败，请稍后重试'
    ElMessage.error(errorMessage)
  } finally {
    saving.value = false
  }
}

// 重置密码
const handleResetPassword = async (user: User) => {
  try {
    const { value: newPassword } = await ElMessageBox.prompt(
      `请输入用户 "${user.name || user.username}" 的新密码`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputValidator: (value) => {
          if (!value || value.length < 6) {
            return '密码长度不能少于6位'
          }
          return true
        }
      }
    )
    
    await resetUserPassword(user.id, newPassword)
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('密码重置失败，请稍后重试')
    }
  }
}

// 切换用户状态
const handleToggleStatus = async (user: User) => {
  try {
    const action = user.status === 'active' ? '禁用' : '启用'
    await ElMessageBox.confirm(
      `确定要${action}用户 "${user.name || user.username}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await toggleUserStatus(user.id)
    ElMessage.success(`用户${action}成功`)
    fetchUsers()
    fetchUserStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换用户状态失败:', error)
      ElMessage.error(`用户状态切换失败，请稍后重试`)
    }
  }
}

// 删除用户
const handleDeleteUser = async (user: User) => {
  // 检查是否为默认admin账户
  if (isDefaultAdmin(user)) {
    ElMessage.warning('默认管理员账户不能删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.name || user.username}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteUser(user.id)
    
    // 处理统一响应格式 {success, data, message}
    if (response && response.data && response.data.success) {
      ElMessage.success(response.data.message || '用户删除成功')
    } else {
      ElMessage.error(response?.data?.message || '用户删除失败')
    }
    
    fetchUsers()
    fetchUserStats()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('用户删除失败，请稍后重试')
    }
  }
}

// 重置表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: undefined,
    username: '',
    email: '',
    name: '',
    phone: '',
    password: '',
    department: '',
    position: '',
    bio: '',
    roles: [],
    status: 'active'
  })
  userFormRef.value?.clearValidate()
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, 'success' | 'danger' | 'info' | 'warning' | 'primary'> = {
    active: 'success',
    inactive: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    active: '激活',
    inactive: '禁用'
  }
  return labelMap[status] || status
}

// 获取角色标签类型（基于角色重要性的通用映射）
const getRoleTagType = (role: string) => {
  return roleStore.getRoleTagType(role)
}

const getRoleLabel = (role: string) => {
  return roleStore.getRoleName(role)
}

// 格式化日期
const formatDate = (date: string | null | undefined) => {
  if (!date) {
    return '暂无数据'
  }
  
  const dateObj = new Date(date)
  if (isNaN(dateObj.getTime())) {
    return '日期格式错误'
  }
  
  return dateObj.toLocaleString('zh-CN')
}

// 检查是否为默认admin账户
const isDefaultAdmin = (user: User) => {
  return user.username === 'admin'
}

// 检查是否为系统管理员（admin角色或admin用户名）
const isSystemAdmin = (user: User) => {
  if (user.username === 'admin') {
    return true
  }
  if (user.roles && Array.isArray(user.roles)) {
    return user.roles.includes('admin')
  }
  return false
}

// 初始化
onMounted(async () => {
  await ensureRoleOptionsLoaded(true).catch(error => {
    console.error('初始化角色数据失败:', error)
  })
  fetchUsers()
  fetchUserStats()
  nextTick(() => {
    updateTableHeight()
  })
  window.addEventListener('resize', handleWindowResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleWindowResize)
})
</script>

<style scoped>
.users-container {
  padding: 20px;
  background: #f0f2f5;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-header-wrapper {
  margin-bottom: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  
  .header-left {
    flex: 1;
    min-width: 0;
  }
  
  .header-right {
    display: flex;
    gap: 12px;
    align-items: center;
    flex-shrink: 0;
  }
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
  min-width: 200px;
}

.page-description {
  margin: 4px 0 0 0;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}


.content-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.content-layout {
  flex: 1;
  display: flex;
  gap: 16px;
  align-items: stretch;
  min-height: 0;
}

.filters-panel {
  width: 260px;
  flex-shrink: 0;
  display: flex;
  min-height: 0;
}


.filters-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
  
  :deep(.el-form-item) {
    margin-bottom: 16px;
    
    .el-form-item__label {
      color: #606266;
      font-weight: 500;
      font-size: 13px;
      padding: 0 0 8px 0;
      line-height: 1.5;
    }
    
    .el-form-item__content {
      line-height: 1.5;
    }
  }
  
  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
  
  /* 快速筛选标签样式 */
  .quick-filters-item {
    margin-bottom: 12px !important;
    
    :deep(.el-form-item__content) {
      margin-left: 0 !important;
    }
  }
  
  /* 操作按钮样式 */
  .filters-actions-item {
    margin-bottom: 0 !important;
    margin-top: 8px;
    
    :deep(.el-form-item__content) {
      margin-left: 0 !important;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  :deep(.el-input),
  :deep(.el-select) {
    font-size: 13px;
  }
}

.quick-filters {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  width: 100%;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  flex-wrap: wrap;
  
  .quick-filters-label {
    font-size: 13px;
    color: #606266;
    font-weight: 500;
    white-space: nowrap;
    line-height: 24px;
  }
  
  .quick-filters-tags {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
    flex: 1;
  }
  
  .filter-tag {
    cursor: pointer;
    transition: all 0.2s;
    margin: 0;
    
    &:hover {
      opacity: 0.8;
      transform: translateY(-1px);
    }
  }
}

.content-layout {
  display: flex;
  gap: 16px;
  height: calc(100vh - 280px);
  min-height: 600px;

  @media (max-width: 1400px) {
    flex-direction: column;
    height: auto;

    .left-sidebar {
      width: 100%;
      height: 300px;
    }

    .middle-sidebar {
      width: 100%;
      height: auto;
      max-height: 500px;
    }

    .right-content {
      width: 100%;
    }

    .filters-panel {
      width: 100%;
    }

    .filters-actions {
      flex-direction: row;
    }

  }
}

.left-sidebar {
  width: 280px;
  min-width: 60px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: width 0.3s ease;
  flex-shrink: 0;
}

.left-sidebar.is-collapsed {
  width: 60px;
}

.department-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.department-card :deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.department-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  min-height: 0;
  overflow: hidden;
}

.department-tree-wrapper {
  padding: 16px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.card-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.left-sidebar.is-collapsed .card-header {
  justify-content: center;
  padding: 0;
}

.left-sidebar.is-collapsed .card-title {
  display: none;
}

.middle-sidebar.is-collapsed .filters-card-header {
  justify-content: center;
  padding: 0;
}

.middle-sidebar.is-collapsed .card-title {
  display: none;
}

.middle-sidebar {
  width: 320px;
  min-width: 60px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: width 0.3s ease;
  flex-shrink: 0;
}

.middle-sidebar.is-collapsed {
  width: 60px;
}

.filters-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.filters-card :deep(.el-card__header) {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.filters-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-height: 40px;
}

.middle-sidebar.is-collapsed .filters-card-header {
  justify-content: center;
  padding: 0;
}

.middle-sidebar.is-collapsed .card-title {
  display: none;
}

.filters-expanded {
  padding-top: 12px;
}

.filters-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.filters-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 12px;
  min-height: 0;
  overflow-y: auto;
}

.filters-panel-compact {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-width: 0;
  overflow: hidden;
}

.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  min-height: 0;
  overflow: hidden;
}

.batch-actions {
  margin-bottom: 12px;
}

.batch-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.batch-info {
  color: #409eff;
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.table-section {
  flex: 1;
  display: flex;
  min-height: 0;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-card :deep(.el-card__header) {
  padding: 16px 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.table-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-header-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  gap: 0;
  min-height: 0;
  overflow: hidden;
}

.table-card :deep(.el-table) {
  flex: 1;
}

.table-scroll {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 12px 16px 0;
  flex-shrink: 0;

  &.top {
    padding-bottom: 8px;
  }

  &.bottom {
    padding-top: 8px;
  }
}

.mr-1 {
  margin-right: 4px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-card) {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-upload-dragger) {
  border-radius: 8px;
}

/* 用户编辑对话框样式 */
.user-dialog {
  .user-form {
    max-height: 70vh;
    overflow-y: auto;
    padding-right: 10px;
  }

  .form-section {
    margin-bottom: 30px;
    padding: 20px;
    background: #fafbfc;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    
    &:last-child {
      margin-bottom: 0;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    
    .el-icon {
      margin-right: 8px;
    }
  }
}
</style>
      color: #409eff;
      font-size: 18px;
    }
    
    span {
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -4px;
        left: 0;
        width: 100%;
        height: 2px;
        background: linear-gradient(90deg, #409eff, transparent);
        border-radius: 1px;
      }
    }
  }

  .el-form-item {
    margin-bottom: 20px;
    
    .el-form-item__label {
      color: #606266;
      font-weight: 500;
    }
    
    .el-input__wrapper {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      
      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
    
    .el-select {
      width: 100%;
      
      .el-select__wrapper {
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        transition: all 0.3s ease;
        
        &:hover {
          box-shadow: 0 0 0 1px #c0c4cc inset;
        }
        
        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }
    }
    
    .el-textarea__inner {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }
      
      &:focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;
    
    .el-button {
      padding: 12px 24px;
      font-weight: 500;
      
      &.el-button--primary {
        background: linear-gradient(135deg, #409eff 0%, #1890ff 100%);
        border: none;
        
        &:hover {
          background: linear-gradient(135deg, #66b1ff 0%, #40a9ff 100%);
        }
      }
    }
  }
}

/* 选择器选项图标样式 */
:deep(.el-select-dropdown__item) {
  display: flex;
  align-items: center;
  
  .el-icon {
    margin-right: 8px;
    color: #909399;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-dialog {
    .el-dialog {
      width: 95% !important;
      margin: 5vh auto !important;
    }
    
    .user-form {
      max-height: 60vh;
    }
    
    .form-section {
      padding: 15px;
      margin-bottom: 20px;
    }
    
    .el-col {
      margin-bottom: 10px;
    }
  }
}

/* 滚动条样式 */
.user-form::-webkit-scrollbar {
  width: 6px;
}

.user-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.user-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  
  &:hover {
    background: #a8a8a8;
  }
}